import os
from pathlib import Path
import time

# app config
MCH_ID = os.environ.get("MCH_ID", None)
ENV_ID = os.environ.get("ENV_ID", None)

if not MCH_ID:
    raise ValueError(f"ENV_ID: {MCH_ID}")

if not ENV_ID:
    raise ValueError(f"ENV_ID: {ENV_ID}")

# sms 邮件服务
SMS_ENABLE = bool(os.environ.get("SMS_SECRET_ID", None))
SMS_SECRET_ID = os.environ.get("SMS_SECRET_ID", None)
SMS_SECRET_KEY = os.environ.get("SMS_SECRET_KEY", None)
SMS_SDK_APP_ID = os.environ.get("SMS_SDK_APP_ID", None)
# 河南省悦码客网络信息科技
SMS_SIGN_NAME = os.environ.get("SMS_SIGN_NAME", None)
# 1778614
SMS_TEMPLATE_ID = os.environ.get("SMS_TEMPLATE_ID", None)

if SMS_ENABLE:
    if not SMS_SECRET_ID:
        raise ValueError(f"SMS_SECRET_ID: {SMS_SECRET_ID}")

    if not SMS_SECRET_KEY:
        raise ValueError(f"SMS_SECRET_KEY: {SMS_SECRET_KEY}")

    if not SMS_SDK_APP_ID:
        raise ValueError(f"SMS_SECRET_KEY: {SMS_SDK_APP_ID}")

    if not SMS_SIGN_NAME:
        raise ValueError(f"SMS_SECRET_KEY: {SMS_SIGN_NAME}")

    if not SMS_TEMPLATE_ID:
        raise ValueError(f"SMS_SECRET_KEY: {SMS_TEMPLATE_ID}")

CUR_PATH = os.path.dirname(os.path.realpath(__file__))
LOG_PATH = os.path.join(os.path.dirname(CUR_PATH), "logs")  # LOG_PATH是存放日志的路径
if not os.path.exists(LOG_PATH):
    os.mkdir(LOG_PATH)  # 如果不存在这个logs文件夹，就自动创建一个

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-_&03zc)d*3)w-(0grs-+t-0jjxktn7k%$3y6$9=x_n_ibg4js6"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = bool(os.environ.get("DEBUG", False))
ALLOWED_HOSTS = ["*"]

CSRF_TRUSTED_ORIGINS = [
    "https://lifa-dev-43463-8-1317259555.sh.run.tcloudbase.com",
    "http://localhost:8000",
    "http://localhost:27081",
    "http://localhost:27082",
]

# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "wxcloudrun",
    "app_base",
    "app_store",
]

import sys

if "createcachetable" in sys.argv:
    INSTALLED_APPS = []

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    # 'django.middleware.csrf.CsrfViewMiddleware',
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "wxcloudrun.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "wxcloudrun.wsgi.application"

# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
AUTH_USER_MODEL = "app_store.WxUser"

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": os.environ.get("MYSQL_DATABASE", "ymk_community"),
        "USER": os.environ.get("MYSQL_USERNAME"),
        "HOST": os.environ.get("MYSQL_ADDRESS").split(":")[0],
        "PORT": os.environ.get("MYSQL_ADDRESS").split(":")[1],
        "PASSWORD": os.environ.get("MYSQL_PASSWORD"),
        "OPTIONS": {"charset": "utf8mb4"},
        "TEST": {
            "NAME": "test_ymk_community",
        },
    }
}

CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.db.DatabaseCache",
        "LOCATION": os.environ.get("MYSQL_CACHE_TABLE", "django_cache"),
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]

LOGGING = {
    "version": 1,
    "disable_existing_loggers": True,
    "formatters": {
        # 日志格式
        "standard": {
            "format": "[%(asctime)s] [%(filename)s:%(lineno)d] [%(module)s:%(funcName)s] "
            "[%(levelname)s]- %(message)s"
        },
        "simple": {"format": "%(levelname)s %(message)s"},  # 简单格式
    },
    # 过滤
    "filters": {},
    # 定义具体处理日志的方式
    "handlers": {
        # 默认记录所有日志
        "default": {
            "level": "INFO",
            "class": "logging.handlers.RotatingFileHandler",
            "filename": os.path.join(
                LOG_PATH, "all-{}.log".format(time.strftime("%Y-%m-%d"))
            ),
            "maxBytes": 1024 * 1024 * 5,  # 文件大小
            "backupCount": 5,  # 备份数
            "formatter": "standard",  # 输出格式
            "encoding": "utf-8",  # 设置默认编码，否则打印出来汉字乱码
        },
        # 输出错误日志
        "error": {
            "level": "ERROR",
            "class": "logging.handlers.RotatingFileHandler",
            "filename": os.path.join(
                LOG_PATH, "error-{}.log".format(time.strftime("%Y-%m-%d"))
            ),
            "maxBytes": 1024 * 1024 * 5,  # 文件大小
            "backupCount": 5,  # 备份数
            "formatter": "standard",  # 输出格式
            "encoding": "utf-8",  # 设置默认编码
        },
        # 控制台输出
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "standard",
        },
        # 输出info日志
        "info": {
            "level": "INFO",
            "class": "logging.handlers.RotatingFileHandler",
            "filename": os.path.join(
                LOG_PATH, "info-{}.log".format(time.strftime("%Y-%m-%d"))
            ),
            "maxBytes": 1024 * 1024 * 5,
            "backupCount": 5,
            "formatter": "standard",
            "encoding": "utf-8",  # 设置默认编码
        },
    },
    # 配置用哪几种 handlers 来处理日志
    "loggers": {
        # 类型 为 django 处理所有类型的日志， 默认调用
        "django": {
            "handlers": ["default", "console"],
            "level": "INFO",
            "propagate": False,
        },
        # log 调用时需要当作参数传入
        "log": {
            "handlers": ["error", "info", "console", "default"],
            "level": "INFO",
            "propagate": True,
        },
    },
}

# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = "zh-Hans"

TIME_ZONE = "Asia/Shanghai"

USE_I18N = True

USE_TZ = True


LOGIN_URL = "/api/mstor_admin/admin_site/login"
LOGOUT_REDIRECT_URL = LOGIN_URL

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = "dj-static/"
STATIC_ROOT = BASE_DIR / "dj-static"


if not os.path.exists(STATIC_ROOT):
    os.mkdir(STATIC_ROOT)

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

LOGS_DIR = "/data/logs/"
